        var prefix = "/sys/classification"

$(function () {
    getTreeData();

});
showButton('#classification');	
showButton('#module_sample_id');	
function getTreeData() {
    $.ajax({
        headers: window.getRequestHears(),
        type: "GET",
        url: window.API_SERVER_URL + "sys/category/tree",
        success: function (tree) {
            createTree(tree);
        }
    });
}

function createTree(tree) {
    var jstree =  $('#jstree').jstree({
        'core': {
            'data': tree
        },
        "plugins": ["search"]
    });
    $('#jstree').jstree().open_all();
}

var initFlag = true;
$('#jstree').on("changed.jstree", function (e, data) {
    if(data && data.node){
        $('#list').show();
        $('#details').hide();

        if (data.selected == -1) {
            $('#paerntCategoryId').val('0');
            $('#paerntCategoryName').val('');
        } else {
            $('#paerntCategoryId').val(data.selected[0]);
            $('#paerntCategoryName').val(data.node.text);
        }
        if(initFlag==true){
            loadData();
        }else{
            $('#exampleTable').bootstrapTable('refresh');
        }
        initFlag = false;
    }
}).on('loaded.jstree', function(e, data){
    var inst = data.instance;
    var obj = inst.get_node(e.target.firstChild.firstChild.lastChild);
    inst.select_node(obj);
});


function loadData() {
    $('#exampleTable')
        .bootstrapTable(
            {
                method: 'get', // 服务器数据的请求方式 get or post
                url: window.API_SERVER_URL + 'sys/category/getChildrenByCategoryId', // 服务器数据的加载地址
                ajaxOptions:{
                      headers:window.getRequestHears(true),
                },
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                // queryParamsType : "limit",
                // //设置为limit则会发送符合RESTFull格式的参数
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                // search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "client", // 设置在哪里进行分页，可选值为"client" 或者
                // "server"
                queryParams: function (params) {
                    var paramsJSON = {
                        // 说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,
                        // 以及所有列的键值对
                        limit: params.offset,
                        offset: params.offset,
                        id: $('#paerntCategoryId').val(),
                    };
                    return paramsJSON;
//					return JSON.stringify(paramsJSON);

                },
                columns: [
                    {
                        field: 'code', // 列字段名
                        title: '编号' // 列标题
                    },
                    {
                        field: 'categoryName',
                        title: '名称',
                        formatter: function (field, row, index) {
                            var e = '<a href="javascript:details(\''+row.id+'\',\''+row.code+'\',\''+row.categoryName+'\',\''+row.description+'\');" >' + field + '</a> ';
                            return e;
                        }
                    },
                    {
                        field: 'description',
                        title: '描述'
                    },
                    {
                        title: '操作',
                        field: 'id',
                        align: 'center',
                        width: '100px',
                        formatter: function (field, row, index) {
                            var e = '<a  class="btn warning btn-sm ' + s_edit_h + '" href="javascript:void(0);" title="编辑" onclick="edit(\''
                                + field
                                + '\')"><img src= "'+SERVER_URL+'static/img/edit.png"></a> ';
                            var delHtml = '';
                            if(row.sysFlag!='1'){
                                delHtml = '<a class="btn warning btn-sm ' + s_remove_h + '" href="javascript:void(0);" title="删除"  mce_href="#" onclick="remove(\''
                                    + field
                                    + '\')"><img src= "'+SERVER_URL+'static/img/remove.png"></a> ';
                            }
                            var permissionsArr = JSON.parse(localStorage.getItem("permissions"));
						
						
						   if(permissionsArr.indexOf('sys:category:edit') == -1){
						    	e = '';
						   }
						
						   if(permissionsArr.indexOf('sys:category:remove') == -1){
						  		delHtml = '';
						   }
						
							
                            return e + delHtml;
                        }
                    }]
            });
}


//新增栏目
function addModule() {
    layer.open({
        type: 2,
        title: '新增栏目',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '400px'],
        content: '../../../templates/system/classification/addModule.html',
        success: function (layero, index) {
            var body = layer.getChildFrame('body', index);//建立父子联系
            $(body).find('input[id=categoryId]').val($('#categoryId').val());
        }
    });
}
function addModuleSuccess(mouduleId, moduleTitle, columnCount) {
    var modulesDiv = $($('#module_sample_id').html());
    $(modulesDiv).find('input[name=columnCount]:first').attr('value',columnCount);
    $(modulesDiv).find('span[name=nameSpan]:first').attr('id',mouduleId);
    $(modulesDiv).find('span[name=nameSpan]:first').text(moduleTitle);
    $(modulesDiv).find('button[name=fieldBtn]:first').click(function () {
        selectFields(mouduleId,moduleTitle);
    });
    $(modulesDiv).find('a[name=editHref]:first').click(function () {
        editModule(mouduleId);
    });

    $(modulesDiv).find('a[name=delHref]:first').click(function () {
        delModule(mouduleId);
    });

    $(modulesDiv).attr('id','module_'+mouduleId);
    $('#modules_div').append(modulesDiv);
}


//编辑栏目
function editModule(moduleId) {
    layer.open({
        type: 2,
        title: '新增栏目',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '400px'],
        content: '../../../templates/system/classification/editModule.html',
        success: function (layero, index) {
            var url = window.API_SERVER_URL + "sys/categoryModule/getById/" + moduleId;
            $.get(url,function (r) {
                if(r){
                    var body = layer.getChildFrame('body', index);//建立父子联系
                    $(body).find('input[id=moduleId]').val(r.id);
                    $(body).find('input[id=title]').val(r.title);
                    $(body).find('input[id=sort]').val(r.sort);
                    $(body).find('input[id=columnCount]').val(r.columnCount);
                    $(body).find('input[name=displayFlag][value="'+r.displayFlag+'"]').attr('checked','checked')
                    $(body).find('input[name=isImport][value="'+r.isImport+'"]').attr('checked','checked')
                }
            });
        }
    });
}


//
function editModuleSuccess(mouduleId, moduleTitle, columnCount) {
    $('#'+mouduleId).text(moduleTitle)
    loadModuleFields($('#categoryId').val());
}

function delModule(moduleId) {
    layer.confirm('确定要删除该栏目？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            headers: window.getRequestHears(),
            url: window.API_SERVER_URL + "sys/categoryModule/remove/" + moduleId,
            type: "post",
            success: function (r) {
                if (r.code == 0) {
                    layer.msg("删除成功");
                    loadModuleFields($('#categoryId').val());
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    });
}


function addSubform() {
    layer.open({
        type: 2,
        title: '新增栏目',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '400px'],
        content: '../../../templates/system/classification/addSubform.html' // iframe的url
    });
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}

function add(id) {
    // iframe层
    layer.open({
        type: 2,
        title: '增加分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '520px'],
        // content : prefix + '/add'
        content: "../../../templates/system/classification/add.html",
        success: function (layero, index) {
            var body = layer.getChildFrame('body', index);//建立父子联系
            $(body).find('input[id=parentId]').val($('#paerntCategoryId').val());
            $(body).find('input[id=parentName]').val($('#paerntCategoryName').val());
        }
    });
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            headers: {"JwtAuthorization": JwtAuthorizations, "Authorization": token},
            url: window.API_SERVER_URL + "sys/category/deleteCategory/" + id,
            type: "GET",
            success: function (r) {
                if (r.code == 0) {
                    layer.msg("删除成功");
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    });
}

function edit(id) {
    var _this = $(this),
        data = _this.parent().siblings(),
        arr = id;
    layer.open({
        type: 2,
        title: '分类修改',
        maxmin: true,
        shadeClose: false,
        area: ['800px', '520px'],
        content: '../../../templates/system/classification/edit.html',
        success: function (layero, index) {
            $.ajax({
                type: 'get',
                headers: {"JwtAuthorization": JwtAuthorizations, "Authorization": token},
                url: window.API_SERVER_URL + 'sys/category/getCategorybyId/' + id,
                success: function (r) {
                    var body = layer.getChildFrame('body', index);//建立父子联系
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    $(body).find('input[id=id]').val(r.id);
                    $(body).find('input[id=parentId]').val(r.parentId);
                    $(body).find('input[id=code]').val(r.code);
                    $(body).find('input[id=categoryName]').val(r.categoryName);
                    $(body).find('input[id=sort]').val(r.sort);
                    $(body).find('textarea[id=description]').val(r.description);
                    if (r.parentId == '0') {
                        $(body).find('input[id=parentName]').val("顶级分类");
                    }
                    else {
                        $.ajax({
                            type: 'get',
                            headers: PRIVATE_HEADERS,
                            url: API_SERVER_URL + 'sys/category/getCategorybyId/' + r.parentId,
                            success: function (y) {
                                $(body).find('input[id=parentName]').val(y.categoryName);
                            }
                        })

                    }
//							iframeWin.initForm();
                }
            });
        }

    });
}

//分类栏目、字段
function details(categoryId,code,categoryName,enableFlag,description) {
    $('#details').show();
    $('#list').hide();

    $('#parentName').text($('#paerntCategoryName').val());
    $('#categoryId').val(categoryId);
    $('#code').text(code);
    $('#categoryName').text(categoryName);
    $('#description').text(description);
    //清空字段
    $('#modules_div').empty();
    loadModuleFields(categoryId);
}

function hideDetails() {
    $('#list').show();
    $('#details').hide();
}

//清空分类详情数据
function resetDetailsData() {

}

//加载分类栏目、字段
function loadModuleFields(categoryId) {
    var url = window.API_SERVER_URL + "sys/categoryModule/getListByCategoryId/"+categoryId;
    $.ajax({
        type: 'get',
        headers: window.getRequestHears(true),
        url:url,
        success: function (data) {
            if(data){
                //清空原有栏目数据
                $('#modules_div').empty();

                $.each(data,function (index,module) {
                    addModuleSuccess(module.id,module.title,module.columnCount);
                    //栏目属性
                    if(module.categoryAttributeList){
                        $.each(module.categoryAttributeList,function (index,attr) {
                            addField(module.id,module.title,attr.fmFieldId,attr.label,attr.renderType,attr.fullLine,attr.rows);
                        });
                    }
                });
            }
        }
    });

}


function selectFields(moduleId,moduleTitle) {
    layer.open({
        type: 2,
        title: '选择字段',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['900px', '500px'],
        content: '../../../templates/system/classification/selectFields.html',
        success: function (layero, index) {
            var body = layer.getChildFrame('body', index);//建立父子联系
            $(body).find('input[id=moduleId]').val(moduleId);
            $(body).find('input[id=moduleTitle]').val(moduleTitle);
        }
    });
}


//选择字段返回
function selectFieldsBack(moduleId, moduleTitle, fields) {
    if (fields) {
        //筛选去除重名属性
        var fieldIds = '';
        var fieldsArray = new Array();
        var repeatFields = '';
        $.each(fields, function (index, field) {
            if ($('input[name="attrId"][id="' + field.id+'"]').length > 0) {
                if (repeatFields != '') {
                    repeatFields += ',';
                }
                repeatFields += field.label;
            } else {
                if (fieldIds != '') {
                    fieldIds += ',';
                }
                fieldIds += field.id;

                fieldsArray.push(field);
            }


        });

        if (repeatFields != '') {
            layer.msg('栏目中已存在' + repeatFields + ' 不允许重复添加');
        }

        if (fieldIds != '') {
            //提交服务器保存
            $.ajax({
                headers: {"Authorization": token},
                url: window.API_SERVER_URL + "sys/categoryAttribute/saveChoosed",
                type: "post",
                data: {
                    'categoryModuleId': moduleId,
                    'fieldIds': fieldIds
                },
                success: function (r) {
                    if (r.code == 0) {
                        $.each(fieldsArray, function (index, newField) {
                            addField(moduleId, moduleTitle,newField.id, newField.label, newField.renderType, newField.fullLine, newField.rows)
                        });
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
        }
    }
}

//添加字段
function addField(moduleId,moduleTitle,fieldId,label, renderType, fullLine, rows) {
    var sampleDom;
    var appendDoms = new Array();
    if('text'==renderType){ //文本框
        sampleDom = $('#text_sample_div').find('table:first').find('tr:first').find('td');
        $.each(sampleDom,function (index,dom) {
           appendDoms.push($(dom).clone());
        });

        $(appendDoms[0]).find('span[name="attrLabel"]:first').text(label);
        $(appendDoms[1]).find('input[name="attrId"]:first').attr('id',fieldId);
        $(appendDoms[1]).find('a[name="delHref"]:first').click(function () {
            removeField(moduleId,fieldId);
        });
        
    }else if('datetime'==renderType){   //日期时间
        sampleDom = $('#datetime_sample_div').find('table:first').find('tr:first').find('td');
        $.each(sampleDom,function (index,dom) {
            appendDoms.push($(dom).clone());
        });

        $(appendDoms[0]).find('span[name="attrLabel"]:first').text(label);
        $(appendDoms[1]).find('input[name="attrId"]:first').attr('id',fieldId);
        $(appendDoms[1]).find('a[name="delHref"]:first').click(function () {
            removeField(moduleId,fieldId);
        });
    }else if('rpopwin'==renderType){   //单选弹窗
        sampleDom = $('#datetime_sample_div').find('table:first').find('tr:first').find('td');
        $.each(sampleDom,function (index,dom) {
            appendDoms.push($(dom).clone());
        });

        $(appendDoms[0]).find('span[name="attrLabel"]:first').text(label);
        $(appendDoms[1]).find('input[name="attrId"]:first').attr('id',fieldId);
        $(appendDoms[1]).find('a[name="delHref"]:first').click(function () {
            removeField(moduleId,fieldId);
        });
    }else if('select'==renderType){   //单选弹窗
        sampleDom = $('#select_sample_div').find('table:first').find('tr:first').find('td');
        $.each(sampleDom,function (index,dom) {
            appendDoms.push($(dom).clone());
        });

        $(appendDoms[0]).find('span[name="attrLabel"]:first').text(label);
        $(appendDoms[1]).find('input[name="attrId"]:first').attr('id',fieldId);
        $(appendDoms[1]).find('a[name="delHref"]:first').click(function () {
            removeField(moduleId,fieldId);
        });
    }else if('textarea'==renderType){   //单选弹窗
        sampleDom = $('#textarea_sample_div').find('table:first').find('tr:first').find('td');
        $.each(sampleDom,function (index,dom) {
            appendDoms.push($(dom).clone());
        });

        $(appendDoms[0]).find('span[name="attrLabel"]:first').text(label);
        $(appendDoms[1]).find('input[name="attrId"]:first').attr('id',fieldId);
        $(appendDoms[1]).find('textarea:first').attr('rows',(rows && rows>0)?rows:1);
        $(appendDoms[1]).find('a[name="delHref"]:first').click(function () {
            removeField(moduleId,fieldId);
        });
    }

    if(appendDoms.length>0){
        var moduleDom = $('#module_'+moduleId);
        //获取栏目表格行数
        var columnCount = $(moduleDom).find('input[name=columnCount]:first').attr('value');
        var trDom = $(moduleDom).find('table:first').find('tr:last');
        if(vm.isShowFun('sys:categoryAttribute:batchRemove') == false){
        	$(appendDoms[1]).find('a[name="delHref"]:first').attr('v-cloak','');
        }
        
        /**
         * 如果没有tr，或者tr已填满td或tr最后一个属性需单独一列，或属性需单独一列，或上个tr的属性需单独一列，则新建tr
         */
        var colspan = $(moduleDom).find('td[name="domTD"]:last').attr('colspan');
        if(trDom.length==0 || $(trDom).find('td').length>=columnCount*2 || fullLine=='1' || colspan==columnCount*2-1){
            trDom = $('<tr></tr>');
            $(moduleDom).find('table[name="attrTable"]').append(trDom);
        }
        $.each(appendDoms,function (index,dom) {
            $(trDom).append(dom);
            if(fullLine=='1' && index==1){
                $(dom).attr('colspan',columnCount*2-1);
            }
        });
    }
}


function removeField(categoryModuleId,filedId) {
    layer.confirm('确定要删除该属性吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            headers:window.getRequestHears(true),
            url: window.API_SERVER_URL + "sys/categoryAttribute/removeByFieldId",
            type: "post",
            data: {
                categoryModuleId: categoryModuleId,
                filedId:filedId
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    //清空字段
                    $('#modules_div').empty();
                    loadModuleFields($('#categoryId').val());
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    });
}

